//
//  CardMainView.m
//  CLBrowser
//
//  Created by 梁慧聪 on 2016/12/20.
//  Copyright © 2021年 梁慧聪. All rights reserved.
//

#import "CLCardMainView.h"
#import "CLCardFlatLayout.h"
#import "CLCardCollectionViewLayout.h"
#import "CLCardCCell.h"
#import "CLCardMainBottomView.h"

#import "CLWebViewManager.h"
#import "CLWebDataView.h"
#import "CLWebContainerView.h"
#import "CLVCMain.h"

#define CardCellIdentifier @"cell"
#define CollectionViewTopMargin 50
#define CollectionViewSideMargin 50

@interface CLCardMainView () <UICollectionViewDelegate, UICollectionViewDataSource, UIGestureRecognizerDelegate,  CLCardBottomClickedDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray<CLWebModel *> *cardArr;
@property (nonatomic, strong) CLCardMainBottomView *cardBottomView;
@property (nonatomic, strong) CLCardFlatLayout *flatLayout;
@property (nonatomic, strong) CLCardCollectionViewLayout *browserLayout;

@end

@implementation CLCardMainView
@synthesize cardArr = _cardArr;

- (NSMutableArray<CLWebModel *> *)cardArr{
    if (!_cardArr) {
        _cardArr = [NSMutableArray array];
    }
    return _cardArr;
}

- (void)setCardsWithArray:(NSArray<CLWebModel *> *)array{
    [self.cardArr removeAllObjects];
    [self.cardArr addObjectsFromArray:array];
    WEAK_SELF;
    dispatch_main_safe_async(^{
        [weakSelf.collectionView reloadData];
    });
}

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self commonInitWithFrame:frame];
    }
    
    return self;
}

- (void)commonInitWithFrame:(CGRect)frame{
    self.backgroundColor = [UIColor whiteColor];
    
    self.collectionView = ({
        self.flatLayout = [CLCardFlatLayout new];
        self.browserLayout = [CLCardCollectionViewLayout new];
        
        UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:self.flatLayout];
        
        collectionView.backgroundColor = [UIColor lightGrayColor];
        collectionView.showsVerticalScrollIndicator = NO;
        collectionView.alwaysBounceVertical = YES;
        collectionView.delegate = self;
        collectionView.dataSource = self;
        [collectionView registerClass:[CLCardCCell class] forCellWithReuseIdentifier:CardCellIdentifier];
        
        [self addSubview:collectionView];
        
        UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognized:)];
        panGestureRecognizer.minimumNumberOfTouches = 1;
        panGestureRecognizer.maximumNumberOfTouches = 1;
        panGestureRecognizer.delegate = self;
        [collectionView addGestureRecognizer:panGestureRecognizer];
        
        collectionView;
    });
    
    self.cardBottomView = ({
        CLCardMainBottomView *bottomView = [[CLCardMainBottomView alloc] initWithFrame:CGRectMake(0, self.height - BOTTOM_TOOL_BAR_HEIGHT, self.width, BOTTOM_TOOL_BAR_HEIGHT)];
        [self addSubview:bottomView];
        bottomView.bottomDelegate = self;
        
        bottomView;
    });
}

- (void)reloadCardMainViewWithCompletionBlock:(CLCompletionBlock)completion {
    WEAK_SELF;
    [[CLWebViewManager sharedInstance] setMultiWebViewOperationBlockWith:^(NSArray<CLWebModel *> *modelArray){
        STRONG_SELF;
        if (strongSelf) {
            [strongSelf setCardsWithArray:modelArray];
            [strongSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:strongSelf.cardArr.count - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
            if (completion) {
                completion();
            }
        }
    }];
}

- (void)changeCollectionViewLayout{
    UICollectionViewLayout *layout = self.collectionView.collectionViewLayout == self.flatLayout ? self.browserLayout : self.flatLayout;
    [self.collectionView setCollectionViewLayout:layout animated:YES completion:^(BOOL finished){
        
    }];
}

#pragma mark - UICollectionViewDelegate

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.item < [self collectionView:collectionView numberOfItemsInSection:0]) {
        CLWebModel *webModel = [self.cardArr objectAtIndex:indexPath.item];
        [self.cardArr removeObjectAtIndex:indexPath.item];
        [self.cardArr addObject:webModel];
        WEAK_SELF;
        [[CLWebViewManager sharedInstance] updateWebModelArray:self.cardArr completion:^{
            STRONG_SELF;
            [strongSelf removeSelfFromSuperView];
        }];
    } else {
        [self removeSelfFromSuperView];
    }
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.cardArr.count;
}

- (CLCardCCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    CLCardCCell *cell = (CLCardCCell *)[collectionView dequeueReusableCellWithReuseIdentifier:CardCellIdentifier forIndexPath:indexPath];
    
    cell.collectionView = collectionView;
    
    WEAK_SELF;
    cell.closeBlock = ^(NSIndexPath *index){
        STRONG_SELF;
        if (strongSelf) {
            [strongSelf.cardArr removeObjectAtIndex:index.item];
            [[CLWebViewManager sharedInstance] updateWebModelArray:strongSelf.cardArr];
            [strongSelf.collectionView deleteItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:index.item inSection:0]]];
            if (strongSelf.cardArr.count == 0) {
                [strongSelf removeSelfFromSuperView];
            }
        }
    };
    
    CLWebModel *webModel = self.cardArr[indexPath.item];
    
    [cell updateWithWebModel:webModel];
    
    return cell;
}

#pragma mark - CardBottomClickedDelegate

- (void)cl_cardBottomBtnClickedWithTag:(CLBottomBtnClicked)tag{
    switch (tag) {
        case CLBottomBtnClickedReturn:
        {
            if ([self.collectionView numberOfItemsInSection:0]) {
                [self.collectionView selectItemAtIndexPath:[NSIndexPath indexPathForItem:[self.collectionView numberOfItemsInSection:0] - 1 inSection:0] animated:YES scrollPosition:UICollectionViewScrollPositionBottom];
            }
            [self removeSelfFromSuperView];
            break;
        }
        case CLBottomBtnClickedAdd:
            [self addCollectionViewCell];
            break;
        default:
            break;
    }
}

- (void)removeSelfFromSuperView{
    [[CLWebViewManager sharedInstance].clContainerView restoreWithCompletionHandler:^(CLWebModel *webModel, CLWebView *webView){
        NSNotification *notify = [NSNotification notificationWithName:kWebTabSwitch object:self userInfo:@{@"webView":webView}];
        [Notifier postNotification:notify];
    } animation:NO];
    
    WEAK_SELF;
    [self.collectionView setCollectionViewLayout:self.flatLayout animated:YES completion:^(BOOL finished){
        STRONG_SELF;
        if (strongSelf) {
            [strongSelf removeFromSuperview];
        }
        [[CLWebViewManager sharedInstance] saveWebModelData];
    }];
}

- (void)addCollectionViewCell{
    NSInteger num = [self.collectionView numberOfItemsInSection:0];
    WEAK_SELF;
    if (num >= 1) {
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:num - 1 inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(.2f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        CLWebModel *webModel = [[CLWebViewManager sharedInstance] getDefaultWebModel];
        [weakSelf.cardArr addObject:webModel];
        [weakSelf.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForItem:num inSection:0]]];
        [[CLWebViewManager sharedInstance] updateWebModelArray:weakSelf.cardArr];
    });
}

#pragma mark - PanGesture Method

- (void)panGestureRecognized:(UIPanGestureRecognizer *)recognizer{    
    CGPoint point = [recognizer locationInView:self.collectionView];
    
    NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:point];
    
    if (recognizer.state == UIGestureRecognizerStateBegan) {
        self.browserLayout.pannedItemIndexPath = indexPath;
        self.browserLayout.panStartPoint = point;
    } else if (recognizer.state == UIGestureRecognizerStateChanged) {
        self.browserLayout.panUpdatePoint = point;
        [self.browserLayout invalidateLayout];
    } else {
        if (fabs(point.x - self.browserLayout.panStartPoint.x) > self.collectionView.frame.size.width / 4 && point.x < self.browserLayout.panStartPoint.x && self.browserLayout.pannedItemIndexPath) {
            NSIndexPath *copyPannedIndexPath = self.browserLayout.pannedItemIndexPath;
            self.browserLayout.pannedItemIndexPath = nil;
            CLCardCCell *cell = (CLCardCCell *)[self.collectionView cellForItemAtIndexPath:copyPannedIndexPath];
            if (cell.closeBlock) {
                cell.closeBlock(copyPannedIndexPath);
                cell.closeBlock = nil;
            }
        }
        else{
            self.browserLayout.pannedItemIndexPath = nil;
            [self.collectionView performBatchUpdates:^{
            } completion:nil];
        }
        
    }
}

#pragma mark - UIGestureRecognizerDelegate

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer
{
    CGPoint velocity = [(UIPanGestureRecognizer *)gestureRecognizer velocityInView:self.collectionView];
    if (fabs(velocity.x) > fabs(velocity.y)) {
        return YES;
    }
    
    return NO;
}

@end
